﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using FinPlusAssembler;
using FinPlusInterfaces;

namespace FinPlusCompCore
{
    public class FinPlusMessaging: FinPlusComponent
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        public event EventHandler<IPod> OnUpdate;

        private readonly ITransport _tran; 

        //construct
        public FinPlusMessaging(string address, int port, string topic = null)
        {
            _tran = IOC.New<ITransport>(address, port);
            _tran.Listener.MessageRecieved += MessageEvent;
            
            if (!string.IsNullOrEmpty(topic))
                Listen(topic);

            IsValid = true;
        }

        //common control interface
        public override void CmdExecute(IPod command)
        {
            try
            {
                CmdCapture(command);              
                Update(command);
            }
            catch (Exception e)
            {
                IsValid = Level.Error.Log(Id, Config, e.Message, e);
            }
        }

        public override void Dispose()
        {
            try
            {
                if(_tran != null)
                    _tran.Dispose();
            }
            catch (Exception e)
            {
                Level.Warning.Log(e.Message, e);
            }
        }

        //public
        public void Listen(string topic)
        {
             _tran.Listen(topic);
        }

        public void Publish(IMessage message)
        {
            _tran.Publish(message);
        }

        //private 
        private void Update(IPod pod)
        {
            if (OnUpdate != null)
                OnUpdate(this, pod);
        }

        //cmds
        private enum Cmds { Update }

        //events 
        private void MessageEvent(object s, EventArgs a)
        {
            CmdExecute(IOC.New<IPod>(((MessageEventArgs)a).Message));
        }
    }
}
